
package com.zcp.wizard;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.util.LinkedList;

public class BatteryManagerActivity extends Activity {
    private Integer brightness = 1;// 屏幕亮度

    private SeekBar seekBar = null;// 调节屏幕亮度的组件

    private Context context = null;

    private MyButtonListenter myButtonListener = null;

    private ToggleButton wifi;

    private ToggleButton gps;

    private ToggleButton bluetooth;

    private ToggleButton net;

    private Button pow;

    private TextView lastPower;

    private TextView batteryTemp;

    private TextView tip;

    private ImageView batteryImageView;

    private AnimationDrawable batteryFrameAnimation;

    private String powok;

    private String powing;

    private String pow10;

    private String pow30;

    private String temp60;

    private String powfull;

    private String opening;// 正在开启%1$s功能

    private String closeing;// 正在关闭%1$s功能

    private String opened;// %1$s功能已开启

    private String closed;// %1$s功能已关闭

    private String bluetoothString;// 蓝牙

    private String networkString;// 移动网络

    private String battery_closed_fail;// 关闭%1$s功能失败

    private String battery_opened_fail;// 开启%1$s功能失败

    private BatteryReceive batteryReceive = new BatteryReceive();

    private LinkedList<String> buttonActionList = new LinkedList<String>();

    private static final int checkButtonStatus = 2;

    private MyCallback myCallback = null;

    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case checkButtonStatus:
                    checkButton();
                    if (myCallback != null) {
                        myCallback.handleMessage(null);
                    }
                    break;
                case Constants.MSG_RETSET_BATTERY_TIP:
                    autoReset();
                    break;
                case Constants.BATTERY_TIP_GAP:
                    tip.setText("");
                    break;
                case Constants.START_MOVIE:
                    if (batteryFrameAnimation != null) {
                        batteryFrameAnimation.start();
                    }
                    break;
            }
        };
    };

    Runnable task = new Runnable() {

        public void run() {
            handler.sendEmptyMessage(checkButtonStatus);
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.batterymanager);
        lastPower = (TextView) findViewById(R.id.surolus);
        batteryTemp = (TextView) findViewById(R.id.temp);
        tip = (TextView) findViewById(R.id.tip);
        batteryImageView = (ImageView) findViewById(R.id.battery);

        powok = getString(R.string.battery_tips_ok);
        powing = getString(R.string.battery_tips_powing);

        pow10 = getString(R.string.battery_tips_bad);
        pow30 = getString(R.string.battery_tips_low);
        temp60 = getString(R.string.battery_tips_hot);

        powfull = getString(R.string.battery_tips_pow_full);

        opening = getString(R.string.battery_opening);

        closeing = getString(R.string.battery_closeing);

        opened = getString(R.string.battery_opened);

        closed = getString(R.string.battery_closed);

        bluetoothString = getString(R.string.bluetooth);

        networkString = getString(R.string.network);

        battery_closed_fail = getString(R.string.battery_closed_fail);

        battery_opened_fail = getString(R.string.battery_opened_fail);

        initializeButtonListener();
        // 这个需要设置最大值为255
        seekBar = (SeekBar) findViewById(R.id.seekBar1);
        initializeSeekBar();

        buttonActionList.add("android.intent.action.ANY_DATA_STATE");
        buttonActionList.add("android.net.wifi.WIFI_STATE_CHANGED");
        buttonActionList.add("android.net.conn.CONNECTIVITY_CHANGE");
        buttonActionList.add("android.intent.action.CLOSE_SYSTEM_DIALOGS");
        buttonActionList.add("com.android.internal.telephony.MOBILE_DATA_CHANGED");
        buttonActionList.add("android.bluetooth.adapter.action.STATE_CHANGED");
        buttonActionList.add("android.bluetooth.intent.action.BLUETOOTH_STATE_CHANGED");
        buttonActionList.add("com.android.settings.GPS_STATUS_CHANGED");
        buttonActionList.add("android.location.PROVIDERS_CHANGED");

        lastPower.setTypeface(Typeface.createFromAsset(getAssets(), "font/WizardThin.ttf"));
        batteryTemp.setTypeface(Typeface.createFromAsset(getAssets(), "font/WizardThin.ttf"));
        MyBroadcastReceiver.register(this);
    }

    @Override
    public void onDestroy() {
        try {
            MyBroadcastReceiver.unRegister(this);
            if (menuPopup != null && menuPopup.isShowing()) {
                menuPopup.dismiss();
            }
            menuPopup = null;
            if (buttonActionList != null) {
                buttonActionList.clear();
            }
            buttonActionList = null;

            if (handler != null) {
                handler.removeCallbacks(task);
                handler.removeCallbacks(taskTip);
                handler.removeMessages(Constants.BATTERY_TIP_GAP);
                handler.removeMessages(Constants.MSG_RETSET_BATTERY_TIP);
                handler.removeMessages(checkButtonStatus);
                handler.removeMessages(Constants.START_MOVIE);
            }
            taskTip = null;
            handler = null;
            task = null;

            brightness = null;

            seekBar = null;

            context = null;

            myButtonListener = null;

            wifi = null;

            gps = null;

            bluetooth = null;

            net = null;

            pow = null;

            lastPower = null;

            batteryTemp = null;

            tip = null;

            batteryImageView = null;

            batteryFrameAnimation = null;

            powok = null;

            powing = null;

            pow10 = null;

            pow30 = null;

            temp60 = null;

            powfull = null;

            opening = null;

            closeing = null;

            opened = null;

            closed = null;

            bluetoothString = null;

            networkString = null;

            battery_closed_fail = null;

            battery_opened_fail = null;

            batteryReceive = null;
            if (buttonActionList != null) {
                buttonActionList.clear();
            }
            buttonActionList = null;

            myCallback = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    /**
     * 检查开关状态
     */
    private void checkButton() {
        wifi.setChecked(WifiUtils.isEnable(context));
        gps.setChecked(GpsUtils.isGPSEnable(context));
        bluetooth.setChecked(BluetoothUtils.isEnabled());
        net.setChecked(Util.getMobileNetworkState(context));
    }

    /**
     * 初始化按钮点击事件监听
     */
    private void initializeButtonListener() {
        context = this;
        myButtonListener = new MyButtonListenter();

        pow = (Button) findViewById(R.id.power);
        pow.setOnClickListener(myButtonListener);

        wifi = (ToggleButton) findViewById(R.id.wifi);

        wifi.setOnClickListener(myButtonListener);

        gps = (ToggleButton) findViewById(R.id.gps);

        gps.setOnClickListener(myButtonListener);

        bluetooth = (ToggleButton) findViewById(R.id.bluetooth);

        bluetooth.setOnClickListener(myButtonListener);

        net = (ToggleButton) findViewById(R.id.net);

        net.setOnClickListener(myButtonListener);
    }

    /**
     * 初始化调节亮度seekBar
     */
    private void initializeSeekBar() {

        seekBar.setOnSeekBarChangeListener(seekListener);

    }

    private static int[] imageIds = new int[] {
            R.drawable.battery_10, R.drawable.battery_20, R.drawable.battery_30,
            R.drawable.battery_40, R.drawable.battery_50, R.drawable.battery_60,
            R.drawable.battery_70, R.drawable.battery_80, R.drawable.battery_90,
            R.drawable.battery_100
    };

    /**
     * 根据电量来更新图片
     * 
     * @param power
     */
    private void updateBatteryPic(int power) {
        if (power < 20) {
            batteryImageView.setBackgroundResource(R.drawable.battery_10);
        }

        for (int i = 10; i > 1; i--) {
            if (power >= i * 10) {
                batteryImageView.setBackgroundResource(imageIds[i - 1]);
                break;
            }
        }

    }

    /**
     * 更新电池信息
     * 
     * @param power
     * @param temp
     */
    private void updateBatteryInfo(int power, int temp, int status, int plug) {
        lastPower.setText("" + power);

        batteryTemp.setText("" + Util.tranTemp(temp, false));
        tip.setTextColor(context.getResources().getColor(R.color.text_other_color)); 
        tip.setText("");
        //充电时候不在提示电量低请及时充电等3257
        if (BatteryManager.BATTERY_STATUS_CHARGING != status) {
            if (power <= Constants.POW_TIP10) {
                tip.setText(pow10);
                tip.setTextColor(context.getResources().getColor(R.color.red));
            } else if (power <= Constants.POW_TIP30) {
                tip.setText(pow30);
            }
        }

        if (BatteryManager.BATTERY_STATUS_FULL == status) {
            if (plug == BatteryManager.BATTERY_PLUGGED_AC) {
                tip.setText(powfull);
            }
        }

        if (temp >= Constants.TEMPERATURE_TIP60 * 10) {// 此事件的优先级高于电量事件
            tip.setText(temp60);
        }
    }

    private boolean running;

    private void undateBatteryStatus(int status, boolean present) {
        // 电池不存在的时候
        if (!present) {
            stopAnimation();
            batteryImageView.setImageResource(0);
            return;
        }
        switch (status) {
            case BatteryManager.BATTERY_STATUS_CHARGING:
                if (present) {
                    startAnimation();
                }
                break;
            case BatteryManager.BATTERY_STATUS_DISCHARGING:
                stopAnimation();
                batteryImageView.setImageResource(0);
                break;
            case BatteryManager.BATTERY_STATUS_FULL:
                batteryImageView.setImageResource(R.drawable.battery_charged);
                stopAnimation();
                break;
            case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                stopAnimation();
                batteryImageView.setImageResource(0);
                break;
        }
    }

    private void startAnimation() {
        running = true;
        batteryImageView.setImageResource(R.drawable.battery_charging);
        batteryImageView.setBackgroundResource(R.anim.powering);
        batteryFrameAnimation = (AnimationDrawable) batteryImageView.getBackground();
        // batteryFrameAnimation.start();
        handler.sendEmptyMessage(Constants.START_MOVIE);
        // Log.i("tag1", "batteryFrameAnimation.start()");
    }

    private void stopAnimation() {
        running = false;
        if (batteryImageView.getBackground() instanceof AnimationDrawable) {
            batteryFrameAnimation = (AnimationDrawable) batteryImageView.getBackground();
            if (batteryFrameAnimation.isRunning()) {
                batteryFrameAnimation.stop();
                batteryFrameAnimation = null;
            }
        }
    }

    /**
     * 一键省电
     * 
     * @param context
     */
    private void keyPower(Context context) {
        pow.setEnabled(false);
        Util.closeThreeSwitcher(context);
        if (seekBar != null) {
            seekBar.setProgress(0);
            adjustBrightness();
            Util.updateBrightnessData(context, brightness);
        }
        tip.setText(powing);
        handler.postDelayed(taskTip, 1000);
    }

    private void autoReset() {
        tip.setText(powok);
        pow.setEnabled(true);
        handler.sendEmptyMessageDelayed(Constants.BATTERY_TIP_GAP, Constants.BATTERY_TIP_GAP);
        
    }

    Runnable taskTip = new Runnable() {

        public void run() {
            handler.sendEmptyMessage(Constants.MSG_RETSET_BATTERY_TIP);
        }
    };

    private void setTiping(String value, boolean switcher) {
        if (switcher) {
            Toast.makeText(this, String.format(closeing, value), Toast.LENGTH_SHORT).show();
            // tip.setText(String.format(closeing, value));
        } else {
            // tip.setText(String.format(opening, value));
            Toast.makeText(this, String.format(opening, value), Toast.LENGTH_SHORT).show();
        }
    }

    private void setTiped(String value, boolean isopen) {
        if (isopen) {
            // tip.setText(String.format(opened, value));
            Toast.makeText(this, String.format(opened, value), Toast.LENGTH_SHORT).show();
        } else {
            // tip.setText(String.format(closed, value));
            Toast.makeText(this, String.format(closed, value), Toast.LENGTH_SHORT).show();
        }
    }

    private class MyButtonListenter implements OnClickListener {
        @Override
        public void onClick(View v) {

            boolean switcher = false;
            myCallback = null;
            switch (v.getId()) {
                case R.id.wifi: {
                    switcher = WifiUtils.isEnable(context);
                    setTiping("WIFI", switcher);
                    wifi.setChecked(switcher);
                    if (WifiUtils.toggleWifi(context)) {
                        myCallback = new MyCallback(true, "WIFI", !switcher);
                    } else {
                        myCallback = new MyCallback(false, "WIFI", !switcher);
                    }

                    break;
                }
                case R.id.gps: {
                    switcher = GpsUtils.isGPSEnable(context);
                    setTiping("GPS", switcher);
                    gps.setChecked(switcher);
                    GpsUtils.toggleGps(context, !switcher);
                    myCallback = new MyCallback(true, "GPS", !switcher);
                    break;
                }
                case R.id.bluetooth: {
                    switcher = BluetoothUtils.isEnabled();
                    setTiping(bluetoothString, switcher);
                    bluetooth.setChecked(switcher);
                    if (BluetoothUtils.toggleBluetooth(context)) {
                        myCallback = new MyCallback(true, bluetoothString, !switcher);
                    } else {
                        myCallback = new MyCallback(false, bluetoothString, !switcher);
                    }
                    break;
                }
                case R.id.net: {
                    switcher = Util.getMobileNetworkState(context);
                    setTiping(networkString, switcher);
                    net.setChecked(switcher);
                    if (Util.toggleNetWork(context,!switcher)) {
                        myCallback = new MyCallback(true, networkString, !switcher);
                    } else {
                        myCallback = new MyCallback(false, networkString, !switcher);
                    }
                    break;
                }
                case R.id.power: {
                    keyPower(context);
                    break;
                }
            }
            // 由于这些是开关按钮，一按就状态变化，而这时比如wifi可能还没有打开，所以由wifi广播来触发按钮状态
            // 同时有些系统改变了广播标识，可能接收不到上述广播，所以增加保险，在一秒后在检查一次
            handler.postDelayed(task, 1000);
        }

    }

    // 主要用来更新tip
    class MyCallback implements Callback {

        boolean mySuccess;

        String myOpereation = "";

        boolean isOpen;

        public MyCallback(boolean success, String opereation, boolean isOpen) {

            mySuccess = success;
            myOpereation = opereation;
            this.isOpen = isOpen;
        }

        @Override
        public boolean handleMessage(Message msg) {
            // "GPS" 需要特殊处理，由于开关当时不能获取成功与否的状态
            if ("GPS".equals(myOpereation)) {
                if (isOpen == GpsUtils.isGPSEnable(context)) {
                    mySuccess = true;
                } else {
                    mySuccess = false;
                }
            }
            if (mySuccess) {
                setTiped(myOpereation, isOpen);
            } else {
                String fail = (isOpen ? battery_opened_fail : battery_closed_fail);
                Toast.makeText(context, String.format(fail, myOpereation), Toast.LENGTH_SHORT)
                        .show();
            }
            handler.sendEmptyMessageDelayed(Constants.BATTERY_TIP_GAP, Constants.BATTERY_TIP_GAP);
            return false;
        }
    }

    // 接收电池信息和开关变化
    private class BatteryReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // Log.i("tag1", "BatteryReceive begin"+intent.getAction());
            if (intent == null) {
                return;
            }
            if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
                int temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
                int lStr = level * 100 / scale;
                // 电池状态
                int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
                        BatteryManager.BATTERY_STATUS_UNKNOWN);

                int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,
                        Constants.BATTERY_UNPLUGED);
                boolean present = intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false);

                // Log.i("tag1", "temp "+temp);
                undateBatteryStatus(status, present);
                updateBatteryInfo(lStr, temp, status, plugged);
                // Log.i("tag1",
                // "BatteryReceive is running move "+running+" status "+
                // status);
                if (!running) {
                    updateBatteryPic(lStr);
                }
            } else if ((buttonActionList != null)
                    && (buttonActionList.contains(intent.getAction()))) {
                checkButton();
            }
        }

    }

    private void adjustBrightness() {
        // 如果自动亮度开关是打开的话，下面就不会有效果。
        brightness = seekBar.getProgress();
        // 由于本activity是在一个tabActivity中所以要先获取父亲再获取窗口，这样设置才会生效
        Activity activity = getParent();
        Util.stopAutoBrightness(activity);
        Util.setBrightness(activity, brightness);

    }

    private OnSeekBarChangeListener seekListener = new OnSeekBarChangeListener() {

        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            // 测试开关，如果是测试,自动化测试程序设置的值fromUser=false
            if (MyBroadcastReceiver.isTestSwitcher) {
                fromUser = true;
            }
            if (fromUser) {
                adjustBrightness();
            }

        }

        // @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // put awesomeness here
        }

        // @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            Util.updateBrightnessData(context, brightness);
        }
    };

    PopupWindow menuPopup;

    View menuLayout;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("menu");// 必须添加一个，其实用不到

        if (null == menuPopup) {

            menuLayout = getLayoutInflater().inflate(R.layout.options_menu, null);

            menuPopup = new PopupWindow(menuLayout, LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);

            menuPopup.setFocusable(true);// 必须，否则无法点击子view
            menuPopup.setOutsideTouchable(true);// 必须，否则点击其它区域无法关闭
            menuPopup.setBackgroundDrawable(new BitmapDrawable());// 同上
            menuPopup.setAnimationStyle(R.style.MenuAnimation);

            menuPopup.setTouchInterceptor(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getY() < 0) {
                        if (menuPopup.isShowing())
                            menuPopup.dismiss();
                    }
                    return false;
                }
            });

            menuLayout.setFocusableInTouchMode(true);// 必须，否则下面的事件不起作用

            menuLayout.setOnKeyListener(new OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // if (Constants.LOG_V)
                    // Log.v(TAG, "onKey(" + v + ", " + event + ")");
                    if ((keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_BACK)
                            && (menuPopup.isShowing())) {
                        menuPopup.dismiss();
                        return true;
                    }
                    return false;
                }
            });

            ((Button) menuLayout.findViewById(R.id.menu_help))
                    .setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            Intent intent = new Intent(BatteryManagerActivity.this,
                                    HelpActivity.class);
                            startActivity(intent);
                            BatteryManagerActivity.this.getParent().overridePendingTransition(
                                    R.anim.zoomin, R.anim.zoomout); // 此为自定义的动画效果，下面两个为系统的动画效果
                        }
                    });

            ((Button) menuLayout.findViewById(R.id.menu_about))
                    .setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            Intent intent = new Intent(BatteryManagerActivity.this,
                                    AboutActivity.class);
                            startActivity(intent);
                            BatteryManagerActivity.this.getParent().overridePendingTransition(
                                    R.anim.zoomin, R.anim.zoomout); // 此为自定义的动画效果，下面两个为系统的动画效果
                            // menuPopup.dismiss();
                        }
                    });

            ((Button) menuLayout.findViewById(R.id.menu_exit))
                    .setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            Util.exit(BatteryManagerActivity.this);
                        }
                    });

            ((Button) menuLayout.findViewById(R.id.menu_update))
                    .setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            // Intent intent = new
                            // Intent(BatteryManagerActivity.this,
                            // UpdateActivity.class);
                            // startActivity(intent);
                            // BatteryManagerActivity.this.getParent().overridePendingTransition(
                            // R.anim.zoomin, R.anim.zoomout);
                            if (menuPopup.isShowing())
                                menuPopup.dismiss();
                          
                            UpdateUtils.updateApp(context);
                        }
                    });

        }

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menuPopup.isShowing())
            menuPopup.dismiss();
        else
            menuPopup.showAtLocation(findViewById(R.id.layoutRoot), Gravity.BOTTOM, 0, 0);
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Log.i("tag1", "onResume");
        if (menuPopup != null && menuPopup.isShowing()) {
            menuPopup.dismiss();
        }

        // 放在这边获取是由于可以当在本页面打开，然后按home按键，打开setting中设置再按home页面打开本程序时候保持和setting中值同步显示。
        brightness = Util.getScreenBrightness(this);
        if (brightness <= (int) (Constants.minBrightness * 255)) {
            brightness = 0;
        }
        seekBar.setProgress(brightness);

        checkButton();

        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        for (String action : buttonActionList) {
            intentFilter.addAction(action);
        }
        registerReceiver(batteryReceive, intentFilter);

    }

    @Override
    protected void onPause() {
        // Log.i("tag1", "onPause");
        stopAnimation();
        unregisterReceiver(batteryReceive);
        super.onPause();
    }

}
